<template>
  <div class="sign-in">
    <el-card class="box-card">
      <div v-if="isDesktop">
        <el-alert
            title="请在手机上扫码签到"
            type="warning"
            description="当前设备为电脑，请在手机上进行扫码签到操作"
            show-icon
            :closable="false"
        />
      </div>
      <div v-else>
        <el-button type="primary" @click="openScanPage" size="large" class="scan-btn">
          <i class="el-icon-camera"></i>
          <span>扫码签到</span>
        </el-button>
      </div>
    </el-card>
    <QRScanner ref="qrScanner" @onScanSuccess="handleScanSuccess"></QRScanner>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElCard, ElAlert, ElButton, ElMessage } from 'element-plus';
import QRScanner from './QRScanner.vue';
import router from "@/router";
import { useRoute } from "vue-router";
import axios from 'axios';
import store from "@/store";

export default {
  components: {
    ElCard,
    ElAlert,
    ElButton,
    QRScanner
  },
  setup() {
    const isDesktop = ref(true);
    const qrScanner = ref(null);
    const route = useRoute();

    // 创建 axios 实例
    const api = axios.create({
      baseURL: store.getters.getBaseURL
    });

    // 请求拦截器
    api.interceptors.request.use(config => {
      const token = sessionStorage.getItem('userToken');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

    // 响应拦截器
    api.interceptors.response.use(
        response => {
          return response;
        },
        error => {
          if (error.response?.status === 401) {
            router.push('/loginAndRegister');
          }
          return Promise.reject(error);
        }
    );

    const openScanPage = () => {
      qrScanner.value.openScanPage();
    };

    const detectDevice = () => {
      const userAgent = navigator.userAgent.toLowerCase();
      const mobileKeywords = ['iphone', 'ipad', 'android', 'windows phone', 'mobile', 'tablet'];
      isDesktop.value = !mobileKeywords.some(keyword => userAgent.includes(keyword));
    };

    // 处理扫描结果
    const handleScanSuccess = (scanResult) => {
      const aid = route.params.id; // 从路由参数中获取aid
      const jobCode = sessionStorage.getItem('jobCode');
      // 组装请求体
      const requestBody = {
        aid: parseInt(aid),
        additionInfo: {
          qrcode: scanResult // 扫描到的二维码数据
        }
      };

      // 使用配置好拦截器的 api 实例发送请求
      api.put('/record/submit', requestBody)
          .then(response => {
            if (response.data.code === 200) {
              ElMessage.success('签到成功');
              setTimeout(() => {
                router.push(`/${jobCode}/personalPage`);
              }, 1000);
            } else {
              ElMessage.error('二维码已过期，请重新扫描');
            }
          })
          .catch(error => {
            console.error('请求错误:', error);
            ElMessage.error('请求失败');
          });
    };

    onMounted(() => {
      const isVerify = route.query.isVerify;
      if (isVerify === '1' && sessionStorage.getItem(`${route.params.id}`) !== '1') {
        router.push({path: `/verification/${isVerify}`, query: {section: route.params.id}});
      }
      detectDevice();
    });

    return {
      isDesktop,
      openScanPage,
      qrScanner,
      handleScanSuccess
    };
  }
};
</script>

<style scoped>
.sign-in {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.box-card {
  width: 400px;
  text-align: center;
}

.scan-btn {
  width: 80%;
  font-size: 18px;
  margin-top: 20px;
}
</style>